package com.zhitan.ems.app.iot.controller;

import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhitan.ems.app.iot.entity.DeviceEntity;
import com.zhitan.ems.app.iot.entity.GroupEntity;
import com.zhitan.ems.app.iot.service.DeviceGroupService;
import com.zhitan.ems.app.iot.service.DeviceService;
import com.zhitan.ems.app.iot.service.GroupService;
import com.zhitan.ems.app.iot.vo.DeviceGroupVO;
import com.zhitan.ems.app.iot.vo.GroupVO;
import com.zhitan.ems.app.iot.vo.TreeGroupSelect;
import com.zhitan.ems.app.iot.wrapper.GroupWrapper;
import com.zhitan.ems.common.annotation.Log;
import com.zhitan.ems.common.core.controller.BaseController;
import com.zhitan.ems.common.core.domain.R;
import com.zhitan.ems.common.enums.BusinessType;
import com.zhitan.ems.common.utils.DateUtils;
import com.zhitan.ems.common.utils.StringUtils;
import com.zhitan.ems.common.utils.poi.ExcelUtil;
import com.zhitan.ems.framework.core.vo.VPage;
import com.zhitan.ems.framework.core.vo.VQueryKit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 设备分组
 * 
 * @author zhitan
 * 
 * @date 2025-09-19 22:15:46
 */
@Api(tags = "设备分组", value = "设备分组")
@RestController
@RequestMapping("intra/iot/group")
public class GroupController extends BaseController {
	@Autowired
	private GroupService groupService;
	@Autowired
	private DeviceGroupService deviceGroupService;
	@Autowired
	private DeviceService deviceService;
	/*
	 * 分组树
	 */
	@ApiOperation(value = "分组树", response = VPage.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "name", value = "标题", paramType = "query", required = false, dataType = "String"), })
	@GetMapping("/listGroupTree")
	@PreAuthorize("@ss.hasPermi('iot:group:list')")
	public R<List<TreeGroupSelect>> listGroupTree(@RequestParam Map<String, Object> params) {
		List<TreeGroupSelect> treeGroupSelects = groupService.selectGroupreeList(params);
		return R.data(treeGroupSelects);
	}

	@ApiOperation(value = "获取分组下所有设备", response = DeviceGroupVO.class)
	@GetMapping("/getDeviceGroupList/{id}")
	@PreAuthorize("@ss.hasPermi('iot:group:list')")
	public R<List<DeviceGroupVO>> getDeviceGroupList(@PathVariable("id") Long id) {
		List<DeviceGroupVO> list = deviceGroupService.getByGroupId(id, 1);
		return R.data(list);
	}

	@Log(title = "新增关联设备", businessType = BusinessType.INSERT)
	@ApiOperation(value = "新增关联设备", response = Boolean.class)
	@PostMapping("/addDevice")
	@PreAuthorize("@ss.hasPermi('iot:devicegroup:save')")
	public R<Boolean> addDevice(@Valid @RequestBody List<DeviceGroupVO> deviceGroupList) {
		for (DeviceGroupVO item : deviceGroupList) {
			if (item.getId() == null) {
				item.setCreateAt(new Date());
				item.setIsDelete(0);
			}
			item.setModeType(0);
			item.setState(1);
			item.setGroupType(0);
			item.setUpdateAt(new Date());
			if(item.getGroupDeviceId()!=null) {
				DeviceEntity device=deviceService.getById(item.getGroupDeviceId());
				if(device!=null) {
					item.setGroupDeviceCode(device.getDeviceCode());
					item.setEnergyType(device.getEnergyType());
				}
			}
			deviceGroupService.saveOrUpdate(item);
		}
		return R.ok(true);
	}
    @ApiOperation(value = "删除管理设备", response = Boolean.class)
    @DeleteMapping("/delDevice")
    @PreAuthorize("@ss.hasPermi('iot:devicegroup:delete')")
    @Log(title = "设备分组", businessType = BusinessType.DELETE)
    public R<Boolean> delDevice(@RequestBody Long[] ids){
        return R.ok(deviceGroupService.removeByIds(Arrays.asList(ids)));
    }

	/**
	 * 列表
	 */
	@ApiOperation(value = "列表", response = VPage.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "name", value = "标题", paramType = "query", required = false, dataType = "String"), })
	@GetMapping("/browse")
	@PreAuthorize("@ss.hasPermi('iot:group:list')")
	public R<VPage<GroupVO>> browse(@RequestParam Map<String, Object> params) {
		QueryWrapper<GroupEntity> queryWrapper = VQueryKit.getQueryWrapperByMap(params, Arrays.asList("name"),
				GroupEntity.class);
		queryWrapper.orderByDesc("group_order");
		queryWrapper.like(StringUtils.isNotNull(params.get("name")), "name", params.get("name"));
		IPage<GroupEntity> pages = groupService.page(VQueryKit.getPage(params), queryWrapper);
		return R.data(GroupWrapper.build().toVPageVO(pages));
	}

	@GetMapping("/listStat")
	@PreAuthorize("@ss.hasPermi('iot:group:list')")
	public R<Map<String, Object>> listStat(@RequestParam Map<String, Object> params) throws ParseException {
		QueryWrapper<GroupEntity> queryWrapper = VQueryKit.getQueryWrapperByMap(params, Arrays.asList("name"),
				GroupEntity.class);
		queryWrapper.select("count(group_id) as total,sum(id) as all");
		queryWrapper.like(StringUtils.isNotNull(params.get("name")), "name", params.get("name"));
		if (params.containsKey("createDate")) {
			queryWrapper.between("create_at",
					DateUtils.getStartOfDate(DateUtils.str_ToDate(params.get("createDate").toString())),
					DateUtils.getEndOfDate(DateUtils.str_ToDate(params.get("createDate").toString())));
		}
		Map<String, Object> stat = groupService.getMap(queryWrapper);
		return R.data(stat);
	}

	@ApiOperation("导出")
	@Log(title = "参数管理", businessType = BusinessType.EXPORT)
	@PreAuthorize("@ss.hasPermi('iot:group:list')")
	@PostMapping("/toExport")
	public void toExport(HttpServletResponse response, @RequestParam Map<String, Object> params) {
		QueryWrapper<GroupEntity> queryWrapper = VQueryKit.getQueryWrapperByMap(params, Arrays.asList("name"),
				GroupEntity.class);
		queryWrapper.orderByDesc("group_order");
		queryWrapper.like(StringUtils.isNotNull(params.get("name")), "name", params.get("name"));
		List<GroupEntity> groupList = groupService.list(queryWrapper);
		ExcelUtil<GroupEntity> util = new ExcelUtil<>(GroupEntity.class);
		util.exportExcel(response, groupList, "参数数据");
	}

	/**
	 * 信息
	 */
	@ApiOperation(value = "信息", response = GroupVO.class)
	@GetMapping("/detail/{groupId}")
	@PreAuthorize("@ss.hasPermi('iot:group:info')")
	public R<GroupVO> detail(@PathVariable("groupId") Long groupId) {
		GroupEntity group = groupService.getById(groupId);
		return R.data(GroupWrapper.build().entityVO(group));
	}

	/**
	 * 保存&更新
	 */
	@Log(title = "设备分组", businessType = BusinessType.ADDANDEDIT)
	@ApiOperation(value = "保存&更新", response = Boolean.class)
	@PostMapping("/submit")
	@PreAuthorize("@ss.hasPermi('iot:group:save')")
	public R<GroupVO> submit(@Valid @RequestBody GroupVO group) {
		if (group.getGroupId() == null) {
			return add(group);
		} else {
			return edit(group);
		}
	}

	@Log(title = "设备分组", businessType = BusinessType.INSERT)
	@ApiOperation(value = "新增", response = Boolean.class)
	@PostMapping("/add")
	@PreAuthorize("@ss.hasPermi('iot:group:save')")
	public R<GroupVO> add(@Valid @RequestBody GroupVO group) {
		if (group.getGroupId() == null) {
			group.setCreateAt(new Date());
			group.setIsDelete(0);
			group.setUpdateAt(new Date());
		}
		if (group.getParentGroupId() == null) {
			group.setParentGroupId(0L);
		}
		if (groupService.save(group)) {
			return R.ok(group);
		}
		return R.error("数据错误");
	}

	@Log(title = "设备分组", businessType = BusinessType.UPDATE)
	@ApiOperation(value = "更新", response = Boolean.class)
	@PostMapping("/edit")
	@PreAuthorize("@ss.hasPermi('iot:group:update')")
	public R<GroupVO> edit(@Valid @RequestBody GroupVO group) {
		group.setUpdateAt(new Date());
		if (group.getParentGroupId() == null) {
			group.setParentGroupId(0L);
		}
		if (groupService.updateById(group)) {
			return R.ok(group);
		}
		return R.error("数据错误");
	}

	/**
	 * 删除
	 */
	@ApiOperation(value = "删除", response = Boolean.class)
	@DeleteMapping("/delete")
	@PreAuthorize("@ss.hasPermi('iot:group:delete')")
	@Log(title = "设备分组", businessType = BusinessType.DELETE)
	public R<Boolean> delete(@RequestBody Long[] groupIds) {
		return R.ok(groupService.removeByIds(Arrays.asList(groupIds)));
	}

}
